<template>
  <div class="reservations-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ authStore.isAdmin ? '预约管理' : '我的预约' }}</span>
        </div>
      </template>

      <el-table :data="reservations" v-loading="loading" stripe>
        <el-table-column 
          v-if="authStore.isAdmin" 
          prop="username" 
          label="用户" 
          width="120" 
        />
        <el-table-column prop="title" label="书名" width="180" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="isbn" label="ISBN" width="130" />
        <el-table-column prop="createdAt" label="预约时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'pending'" type="warning">待处理</el-tag>
            <el-tag v-else-if="row.status === 'available'" type="success">可借阅</el-tag>
            <el-tag v-else type="info">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!authStore.isAdmin && (row.status === 'pending' || row.status === 'available')"
              type="danger"
              size="small"
              @click="handleCancelReservation(row)"
            >
              取消预约
            </el-button>
            <el-button
              v-if="!authStore.isAdmin && row.status === 'available'"
              type="primary"
              size="small"
              @click="handleBorrowFromReservation(row)"
            >
              立即借阅
            </el-button>
            <span v-if="authStore.isAdmin || (row.status !== 'pending' && row.status !== 'available')">-</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import { reservationAPI, borrowAPI } from '../services/api'

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const authStore = useAuthStore()
const reservations = ref([])
const loading = ref(false)

const fetchReservations = async () => {
  loading.value = true
  try {
    const response = await reservationAPI.getReservations()
    reservations.value = response.reservations || []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取预约列表失败')
  } finally {
    loading.value = false
  }
}

const handleCancelReservation = async (reservation) => {
  try {
    await ElMessageBox.confirm(`确定要取消预约《${reservation.title}》吗？`, '确认取消预约', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await reservationAPI.cancelReservation(reservation.id)
    ElMessage.success('取消预约成功')
    await fetchReservations()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '取消预约失败')
    }
  }
}

const handleBorrowFromReservation = async (reservation) => {
  try {
    await ElMessageBox.confirm(`确定要借阅《${reservation.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await borrowAPI.borrowBook(reservation.bookId)
    ElMessage.success('借阅成功')
    await fetchReservations()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '借阅失败')
    }
  }
}

onMounted(() => {
  fetchReservations()
})
</script>

<style scoped>
.reservations-container {
  height: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
}
</style>

